#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
改进的第1阶段验证脚本 - 增加调试信息和更长等待时间
"""

import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

class ImprovedStage1Verifier:
    """改进的第1阶段验证器"""
    
    def __init__(self):
        self.setup_driver()
        self.discovered_cars = set()
        
    def setup_driver(self):
        """设置Chrome WebDriver"""
        chrome_options = Options()
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15')
        
        service = Service(ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.wait = WebDriverWait(self.driver, 15)  # 增加等待时间
    
    def debug_page_state(self, step_name):
        """调试页面状态"""
        print(f"\n🔍 调试信息 - {step_name}:")
        
        # 检查页面标题
        try:
            title = self.driver.title
            print(f"   📄 页面标题: {title}")
        except:
            print(f"   ❌ 无法获取页面标题")
        
        # 检查URL
        try:
            current_url = self.driver.current_url
            print(f"   🌐 当前URL: {current_url}")
        except:
            print(f"   ❌ 无法获取当前URL")
        
        # 查找车型元素
        try:
            car_elements = self.driver.find_elements(By.CSS_SELECTOR, 'div[data-cy]')
            print(f"   🚗 找到data-cy元素: {len(car_elements)} 个")
            
            if car_elements:
                for element in car_elements[:5]:  # 只显示前5个
                    data_cy = element.get_attribute('data-cy')
                    is_visible = element.is_displayed()
                    print(f"      - {data_cy}: {'可见' if is_visible else '隐藏'}")
        except Exception as e:
            print(f"   ❌ 查找车型元素出错: {e}")
        
        # 查找按钮
        try:
            buttons = self.driver.find_elements(By.CSS_SELECTOR, 'button[action]')
            print(f"   🔘 找到action按钮: {len(buttons)} 个")
            
            for button in buttons:
                action = button.get_attribute('action')
                disabled = button.get_attribute('aria-disabled')
                print(f"      - action='{action}': {'禁用' if disabled == 'true' else '可用'}")
        except Exception as e:
            print(f"   ❌ 查找按钮出错: {e}")
    
    def improved_verification(self):
        """改进的验证流程"""
        try:
            print("🔍 开始改进的第1阶段验证")
            print("="*60)
            
            # 访问页面
            url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
            print(f"📖 访问页面: {url}")
            self.driver.get(url)
            
            # 初始等待
            print(f"⏳ 等待页面加载...")
            time.sleep(5)
            
            # 调试初始状态
            self.debug_page_state("页面初始加载")
            
            # 处理Cookie
            print(f"\n🍪 处理Cookie...")
            self.handle_cookies()
            time.sleep(2)
            
            # 再次调试状态
            self.debug_page_state("Cookie处理后")
            
            # 等待车型元素加载
            print(f"\n⏳ 等待车型元素加载...")
            self.wait_for_car_elements()
            
            # 最终调试状态
            self.debug_page_state("车型元素等待后")
            
            # 尝试发现车型
            print(f"\n🔄 尝试发现车型...")
            self.discover_cars_with_navigation()
            
            # 最终报告
            print(f"\n📊 最终结果:")
            print(f"   发现车型: {len(self.discovered_cars)} 个")
            print(f"   车型列表: {sorted(list(self.discovered_cars))}")
            
            success = len(self.discovered_cars) == 7 and 'ST Edition' in self.discovered_cars
            
            if success:
                print(f"   ✅ 验证成功!")
            else:
                print(f"   ⚠️  验证未完全成功")
                if len(self.discovered_cars) != 7:
                    print(f"      - 车型数量: {len(self.discovered_cars)} != 7")
                if 'ST Edition' not in self.discovered_cars:
                    print(f"      - 缺少 'ST Edition'")
            
            return success
            
        except Exception as e:
            print(f"❌ 验证过程出错: {e}")
            return False
        finally:
            input("按Enter键关闭浏览器...")
            self.driver.quit()
    
    def handle_cookies(self):
        """处理Cookie"""
        try:
            # 强制隐藏cookie相关元素
            cookie_script = """
                var cookieElements = document.querySelectorAll('[class*="cookie"], [class*="Cookie"], [class*="consent"], [id*="cookie"], [id*="Cookie"]');
                cookieElements.forEach(function(el) {
                    el.style.display = 'none';
                });
                console.log('Hidden ' + cookieElements.length + ' cookie elements');
            """
            self.driver.execute_script(cookie_script)
            print(f"   ✓ 执行Cookie隐藏脚本")
            
        except Exception as e:
            print(f"   ❌ Cookie处理出错: {e}")
    
    def wait_for_car_elements(self):
        """等待车型元素加载"""
        try:
            # 方法1: 等待data-cy元素出现
            print(f"   📍 方法1: 等待data-cy元素...")
            try:
                self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div[data-cy]')))
                print(f"   ✓ 检测到data-cy元素")
            except:
                print(f"   ❌ 未检测到data-cy元素")
            
            # 方法2: 等待ProductTile元素
            print(f"   📍 方法2: 等待ProductTile元素...")
            try:
                self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '[class*="ProductTile"]')))
                print(f"   ✓ 检测到ProductTile元素")
            except:
                print(f"   ❌ 未检测到ProductTile元素")
            
            # 方法3: 等待按钮变为可用
            print(f"   📍 方法3: 等待导航按钮...")
            try:
                buttons = self.driver.find_elements(By.CSS_SELECTOR, 'button[action]')
                if buttons:
                    print(f"   ✓ 找到 {len(buttons)} 个导航按钮")
                else:
                    print(f"   ❌ 未找到导航按钮")
            except:
                print(f"   ❌ 导航按钮检测出错")
            
            # 额外等待时间让页面完全加载
            print(f"   ⏳ 额外等待10秒...")
            time.sleep(10)
            
        except Exception as e:
            print(f"   ❌ 等待车型元素时出错: {e}")
    
    def discover_cars_with_navigation(self):
        """使用导航发现车型"""
        try:
            max_clicks = 15
            click_count = 0
            
            while click_count < max_clicks:
                print(f"\n   🔄 第 {click_count + 1} 轮发现:")
                
                # 获取当前页面的车型
                current_cars = self.get_current_cars()
                new_found = 0
                
                for car in current_cars:
                    if car['name'] not in self.discovered_cars:
                        self.discovered_cars.add(car['name'])
                        new_found += 1
                        print(f"      ✓ 新发现: {car['name']} ({'可见' if car['visible'] else '隐藏'})")
                
                if new_found == 0:
                    print(f"      - 无新发现")
                
                print(f"      📊 累计: {len(self.discovered_cars)} 个车型")
                
                # 检查分页信息
                pagination = self.get_pagination_info()
                if pagination:
                    print(f"      📄 分页: {pagination}")
                
                # 如果找到7个车型，成功
                if len(self.discovered_cars) >= 7:
                    print(f"      🎉 达到目标数量!")
                    break
                
                # 尝试点击下一页
                if self.click_next():
                    print(f"      ✓ 点击下一页成功")
                    click_count += 1
                    time.sleep(3)  # 增加等待时间
                else:
                    print(f"      ❌ 无法点击下一页")
                    break
            
        except Exception as e:
            print(f"   ❌ 车型发现过程出错: {e}")
    
    def get_current_cars(self):
        """获取当前车型"""
        try:
            cars = []
            
            # 查找所有可能的车型元素
            selectors = [
                'div[data-cy][class*="ProductTile"]',
                'div[data-cy]',
                '[class*="ProductTile"]'
            ]
            
            for selector in selectors:
                elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                if elements:
                    for element in elements:
                        try:
                            name = element.get_attribute('data-cy')
                            if name and name not in [car['name'] for car in cars]:
                                cars.append({
                                    'name': name,
                                    'visible': element.is_displayed(),
                                    'element': element
                                })
                        except:
                            pass
                    break  # 找到元素就停止
            
            return cars
            
        except Exception as e:
            print(f"      获取车型时出错: {e}")
            return []
    
    def get_pagination_info(self):
        """获取分页信息"""
        try:
            # 在按钮容器中查找
            buttons = self.driver.find_elements(By.CSS_SELECTOR, 'button[action]')
            for button in buttons:
                try:
                    parent = button.find_element(By.XPATH, '..')
                    text = parent.text.strip()
                    if 'of' in text.lower():
                        return text
                except:
                    pass
            
            # 在页面中搜索
            import re
            page_text = self.driver.find_element(By.TAG_NAME, 'body').text
            matches = re.findall(r'\d+-?\d*\s+of\s+\d+', page_text, re.IGNORECASE)
            if matches:
                return matches[0]
            
            return None
            
        except Exception as e:
            return None
    
    def click_next(self):
        """点击下一页"""
        try:
            next_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="next"]')
            disabled = next_button.get_attribute('aria-disabled')
            
            if disabled != 'true':
                self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", next_button)
                time.sleep(1)
                next_button.click()
                return True
            else:
                return False
                
        except Exception as e:
            print(f"        点击下一页出错: {e}")
            return False

def main():
    """主函数"""
    verifier = ImprovedStage1Verifier()
    success = verifier.improved_verification()
    
    if success:
        print("\n🎉 改进验证成功！")
    else:
        print("\n❌ 改进验证未完全成功！")

if __name__ == "__main__":
    main()
